package io.renren.modules.weixin.controller;

 

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.RedirectView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import io.renren.common.utils.CommonUtils;
import io.renren.common.utils.IPUtils;
import io.renren.common.utils.R;
import io.renren.modules.mem_token.service.V9MemTokenService;
import io.renren.modules.member.entity.V9MemberEntity;
import io.renren.modules.member.service.V9MemberService;
import io.renren.modules.weixin.entity.AccessToken;
import io.renren.modules.weixin.util.WeixinUtil;

@Controller
@RequestMapping("index/weixin")
public class WeixinController {

	private String TOKEN = "good";
	//private static Logger log = LoggerFactory.getLogger(WeixinController.class);
	@Autowired
	private V9MemberService v9MemberService;
	@Autowired
	private V9MemTokenService v9MemTokenService;

	@ResponseBody
	@RequestMapping("/do")
	public String weixin(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp,
			@RequestParam("nonce") String nonce, @RequestParam("echostr") String echostr) {
		// 排序
		String sortString = sort(TOKEN, timestamp, nonce);
		// 加密
		String myString = sha1(sortString);
		// 校验
		if (myString != null && myString != "" && myString.equals(signature)) {
			System.out.println("签名校验通过");
			// 如果检验成功原样返回echostr，微信服务器接收到此输出，才会确认检验完成。
			return echostr;
		} else {
			System.out.println("签名校验失败");
			return "";
		}
	}

	@RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
	public String wxLogin(HttpServletRequest request, HttpServletResponse response) throws ParseException {
		// 这个url的域名必须要进行再公众号中进行注册验证，这个地址是成功后的回调地址
		String backUrl = WeixinUtil.backUrl;
		String appid = WeixinUtil.APPID;
		// 第一步：用户同意授权，获取code
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + backUrl
				+ "&response_type=code" + "&scope=snsapi_userinfo" + "&state=STATE#wechat_redirect";
		return "redirect:" + url;
	}

	@GetMapping("/wxcallback")
	public RedirectView wxcallback(String code, ModelMap map,HttpServletRequest req) throws IOException {
		String appid = WeixinUtil.APPID;
		String appsecret=WeixinUtil.APPSECRET;
		String redirectUrl = WeixinUtil.redirectUrl;
		R r = R.ok();
		// 第二步：通过code换取网页授权access_token
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret
				+ "&code=" + code + "&grant_type=authorization_code";
		com.alibaba.fastjson.JSONObject jsonObject = WeixinUtil.doGet(url);

		String openid = jsonObject.getString("openid");
		String access_Token = jsonObject.getString("access_token");

		//System.out.println(jsonObject);

		// 第四步：拉取用户信息(需scope为 snsapi_userinfo)
		url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_Token + "&openid=" + openid
				+ "&lang=zh_CN";
		com.alibaba.fastjson.JSONObject userInfo = WeixinUtil.doGet(url);
		//System.out.println("UserInfo:" + userInfo);
		String unionid = userInfo.getString("openid");
		String headimg = userInfo.getString("headimgurl");
		String nickname = userInfo.getString("nickname");
		V9MemberEntity memberEntity = new V9MemberEntity();
		System.out.println("unionid:" + unionid);
		System.out.println("userInfo:" + userInfo.toJSONString());
		V9MemberEntity user = v9MemberService.getOne(new QueryWrapper<V9MemberEntity>().eq("unionid", unionid));
		 //System.out.println(user.toString());
		 //System.out.println(user==null);
		if (user != null) {
			// 账号锁定
			if (user.getIslock() != 0) {
				// return R.error("账号已被锁定,请联系管理员");
			}
			if (user.getLahei() != 0) {
				// return R.error("账号已被拉黑,请联系管理员");
			}
			if (user.getFenghao() != 0) {
				// return R.error("账号已被封,请联系管理员");
			}
			// 生成token，并保存到数据库
			r = v9MemTokenService.createToken(user.getUserid());
			r.put("username", user.getUsername());
			// return r;
		} else {
			memberEntity.setUnionid(unionid);
			memberEntity.setHeadimg(headimg);
			memberEntity.setNickname(nickname);
			memberEntity.setRegdate(CommonUtils.getCurrentTimeStamp());
			memberEntity.setLastdate(CommonUtils.getCurrentTimeStamp());
			memberEntity.setRegip(IPUtils.getIpAddr(req));
			Boolean flag = true;
			while (flag) {
				String username = CommonUtils.createUserName();
				user = v9MemberService.getOne(new QueryWrapper<V9MemberEntity>().eq("username", username));
				if (user == null) {
					flag = false;
					memberEntity.setUsername(username);
				}
			}

			Integer inserGetId = v9MemberService.inserGetId(memberEntity);
			r = v9MemTokenService.createToken(inserGetId);
			r.put("username", memberEntity.getUsername());
			// R r = R.ok().put("token", token).put("expire", expireTime);

		}
		String token = (String) r.get("token");
		String expire = CommonUtils.dateToString((Date) r.get("expire"));
		String username = (String) r.get("username");
		redirectUrl = redirectUrl + "?token=" + token + "&expire=" + expire + "&username=" + username;
		 
		System.out.println(redirectUrl);
		RedirectView redirectTarget = new RedirectView();
		redirectTarget.setContextRelative(true);
		redirectTarget.setUrl(redirectUrl);
		return redirectTarget;
		 
	}
 

	 
 

	public String sort(String token, String timestamp, String nonce) {
		String[] strArray = { token, timestamp, nonce };
		Arrays.sort(strArray);
		StringBuilder sb = new StringBuilder();
		for (String str : strArray) {
			sb.append(str);
		}

		return sb.toString();
	}

	public String sha1(String str) {
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			digest.update(str.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static void main(String[] args) throws ClientProtocolException, IOException {
		AccessToken token = WeixinUtil.getAccessToken();
		System.out.println("Access_Token为:" + token.getToken());
		System.out.println("有效时间为：" + token.getExpiresIn());
		String menu = net.sf.json.JSONObject.fromObject(WeixinUtil.initMenu()).toString();
		int result = WeixinUtil.createMenu(token.getToken(), menu);
		if (result == 0) {
			System.out.println("菜单创建成功！");
		} else {
			System.out.println("菜单创建失败！");
		}
	}

}
